﻿using System.Collections.Generic;
using PlayMyLife.Definitions.StoryEvent;
using PlayMyLife.ModelInterface;

namespace PlayMyLife.ModelLocal {
    public class LocalPlaceManager : IPlaceManager {

        public PlaceData GetPlaceData(long id) {
            places.TryGetValue(id, out var ret);
            return ret;
        }

        public bool AddPlaceData(PlaceData data) {
            if(places.ContainsKey(data.id)) {
                return false;
            }
            places.Add(data.id, data);
            persons.Add(data.id, new List<long>());
            return true;
        }

        public long[] GetAllPersonsAtPlace(long id) {
            persons.TryGetValue(id, out var ret);
            return ret.ToArray();
        }

        public bool MoveTo(long placeId, long roleId) {
            if(personPlaceRecords.TryGetValue(roleId, out var personOldPlace)) {
                if(persons[personOldPlace].Remove(roleId)) {
                    return false;
                }
                personPlaceRecords.Remove(roleId);
            }

            if(!persons.ContainsKey(placeId)) {
                persons.Add(placeId, new List<long>());
            }
            var placeRoles = persons[placeId];
            if(placeRoles.Contains(roleId)) {
                return false;
            }
            placeRoles.Add(roleId);
            personPlaceRecords.Add(roleId, placeId);
            return true;
        }

        private readonly Dictionary<long, PlaceData> places = new();
        private readonly Dictionary<long, List<long>> persons = new();
        private readonly Dictionary<long, long> personPlaceRecords = new();
    }
}